from zope.interface import implements
from zope.component import getMultiAdapter
from zope.component import queryUtility
from Acquisition import aq_inner
from plone.memoize.instance import memoize
from zope.i18n.interfaces import ITranslationDomain
from Products.CMFCore.utils import getToolByName

from plone.portlets.interfaces import IPortletDataProvider
from plone.app.portlets.portlets import base

from plone.portlet.collection.collection import ICollectionPortlet
from plone.portlet.collection.collection import Assignment as baseAssignment
from plone.portlet.collection.collection import Renderer as baseRenderer


# TODO: If you define any fields for the portlet configuration schema below
# do not forget to uncomment the following import
from zope import schema
from zope.formlib import form

from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from my315ok.fangcan import fangcanMessageFactory as _
from my315ok.products import productsMessageFactory as _a
from my315ok.fangcan.interfaces import Ihouse

# TODO: If you require i18n translation for any of your schema fields below,
# uncomment the following to import your package MessageFactory
#from my315ok.portlet.photocollection import photocollectionMessageFactory as _


class Ifangcanportlet(IPortletDataProvider):
    """A portlet

    It inherits from IPortletDataProvider because for this portlet, the
    data that is being rendered and the portlet assignment itself are the
    same.
    """

    # TODO: Add any zope.schema fields here to capture portlet configuration
    # information. Alternatively, if there are no settings, leave this as an
    # empty interface - see also notes around the add form and edit form
    # below.

    header = schema.TextLine(title=_a(u"Portlet header"),
                             description=_a(u"Title of the rendered portlet"),
                             required=True)
    header2 = schema.TextLine(title=_a(u"Portlet header"),
                             description=_a(u"Title of the rendered portlet"),
                             required=True)
    header3 = schema.TextLine(title=_a(u"Portlet header"),
                             description=_a(u"Title of the rendered portlet"),
                             required=True)

#    target_collection = schema.Choice(title=_a(u"Target collection"),
#                                  description=_a(u"Find the collection which provides the items to list"),
#                                  required=True,
#                                  source=SearchableTextSourceBinder({'object_provides' : IATTopic.__identifier__},
#                                                                    default_query='path:'))

    limit = schema.Int(title=_a(u"Limit"),
                       description=_a(u"Specify the maximum number of items to show in the portlet. "
                                       "Leave this blank to show all items."),
                       required=False)
    rows = schema.Int(title=_a(u"rows"),
                       description=_a(u"Specify the rows number."),
                       required=False)
    cols = schema.Int(title=_a(u"cols"),
                       description=_a(u"Specify the cols number."),
                       required=False)
    show_more = schema.Bool(title=_a(u"Show more... link"),
                       description=_a(u"If enabled, a more... link will appear in the footer of the portlet, "
                                      "linking to the underlying Collection."),
                       required=True,
                       default=True)
    wordsnum = schema.Int(title=_a(u"number"),
                       description=_a(u"Specify the maximum number of words to show as title. "
                                       "Leave this blank to show all items."),
                       default=36,
                       required=False)
    previewmode = schema.Choice(
        title=_a(u"image size"),
        description=_a(u"Choose source image size"),
        required = True,
        default = "thumb",       
        vocabulary = 'product.ImageSizeVocabulary' )


class Assignment(baseAssignment):
    """Portlet assignment.

    This is what is actually managed through the portlets UI and associated
    with columns.
    """

    implements(Ifangcanportlet)

    # TODO: Set default values for the configurable parameters here

    # some_field = u""

    header = u""
    header2 = u""
    header3 = u""
#    target_collection = None
    limit = 5
    rows = 1
    cols = 1
    show_more = True
    previewmode = u"thumb"
    wordsnum = 32


    def __init__(self, header=u"", wordsnum=32, limit=None,rows=1,\
                 header2=u"",header3=u"",cols=1,show_more=True, previewmode=u"thumb"):
        self.header = header
        self.header2 = header2
        self.header3 = header3
        self.limit = limit
        self.rows = rows
        self.cols = cols
        self.show_more = show_more
        self.wordsnum = wordsnum
        self.previewmode = previewmode

    @property
    def title(self):
        """This property is used to give the title of the portlet in the
        "manage portlets" screen.
        """
        return _(u"fangcanPortlet")


class Renderer(baseRenderer):
    """Portlet renderer.

    This is registered in configure.zcml. The referenced page template is
    rendered, and the implicit variable 'view' will refer to an instance
    of this class. Other methods can be added and referenced in the template.
    """

    render = ViewPageTemplateFile('fangcanportlet.pt')
    
    @property
    def available(self):
#        import pdb
#        pdb.set_trace()
        return bool(len(self.results("0")) >= (self.data.rows * self.data.cols))

    def ifrenderpanel(self,category):
        lenth = len(self.results(category))
        return bool(lenth > self.data.cols)
                    
    @memoize
    def rows(self,category):
        total = len(self.results(category))
        cols = self.cols()
        out = int((total + cols - 1)/cols)             
#        rows = self.data.rows
        return out
        
    def cols(self):
        cols = self.data.cols
        return cols
    

    def results(self,category):
        """ Get the actual result brains from the collection. 
            This is a wrapper so that we can memoize if and only if we aren't
            selecting random items."""
        
        return self.fetchinfo(category)

      
        
    @memoize
    def fetchinfo(self,category):
#        import pdb
#        pdb.set_trace()

        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')        
        lm = self.data.limit
        if lm == None:
            lm = self.rows(category) * self.cols()       
        result = []
        
        brains = catalog(object_provides=Ihouse.__identifier__,
                             category=category,
                             review_status='published',
                             sort="modified",
                             sort_order='reverse'
                             )
        
        if lm > 0 and lm < len(brains):
            brains = brains[:lm]
        return brains
    @memoize   
    def main_parameters(self,category):
        """ fetch product parameters""" 
#        import pdb
#        pdb.set_trace()             
        brains = self.results(category)
        sc = self.data.previewmode
        goods = []
        util = queryUtility(ITranslationDomain, 'my315ok.fangcan')
        rooms = util.translate(_(u"rooms"),
                                       target_language="zh",
                                       default="rooms")
        tings = util.translate(_(u"tings"),
                                       target_language="zh",
                                       default="tings")
    
        if len(brains) >0:            
            for bs in brains:              
                tmp = self.add_paras(bs,sc,rooms,tings)
                goods.append(tmp)
        return goods
    
    # here is set local varible item avoid by overed.
    @memoize
    def add_paras(self,obj,scale,rooms,tings):
        """given a multiproducts brain,fetch products parameters"""
#        import pdb
#        pdb.set_trace()
        try:
            le = self.data.wordsnum
        except:
            le = 36
        item={}
        item['title'] =  self.cropTitle(obj.Title, 4)        
        item['houseno'] = obj.House_no
        try:
            r = str(obj.Room)
        except:
            r = ""
        try:
            d = str(obj.Drawing_room)
        except:
            d = ""
        if r !="" and d !="":            
            item['housetype'] = r + rooms + d + tings
        elif d =="":
            item['housetype'] = r + rooms
        else:
            item['housetype'] = d + tings                        
                
        try:
            s = int(obj.Mianji)
        except:
            s = 100        
        try:
            u = int(obj.Sale_unitprice)
        except:
            u = 3000
        item['mianji'] = s
        item['unitprice'] = u
        # unitprice yuan turn to wyuan
        item['totalprice'] = s*u/10000
        re = obj.Remark
        try:
            lt = len(re)
            if lt > le:         
                item['remark'] = self.cropTitle(re, le)
            else:
                item['remark'] = re
                
        except:
            item['remark'] =""
            
#        item['img_url'] = obj.absolute_url() + "/base_view"
        item['url'] =  obj.getURL()
        item['image'] =  self.get_goods_img(obj, scale)
        return item       
        
        
    @memoize
    def get_goods_img(self,obj,scale):
#        import pdb
#        pdb.set_trace()
        
        base = obj.getURL()
        tl = obj.Title

        url = base + "/image_" + scale
        portal_state = getMultiAdapter((self.context, self.request), name=u'plone_portal_state')
        portal = portal_state.portal()
        p_url = portal.absolute_url()
        existimg = portal.unrestrictedTraverse(url, default=None)
        if existimg == None:
            url = p_url + "/++resource++fcwatermark_%s.jpg" % scale 
        imgtag ="<img src ='%s' alt='%s'/>" % (url,tl)
  
        return imgtag 
    
    @memoize
    def cropTitle(self,text, length, ellipsis='...'):
        if length == 0 or length == None:
            return text
        context = aq_inner(self.context)
        pview = getMultiAdapter((context,self.request),name=u"plone")
#        pview = getMultiAdapter((self.parent(), self.request), name=u'earthqk_event_view')
        croped = pview.cropText(text, length)
        return croped                     

class AddForm(base.AddForm):
    """Portlet add form.

    This is registered in configure.zcml. The form_fields variable tells
    zope.formlib which fields to display. The create() method actually
    constructs the assignment that is being added.
    """
    form_fields = form.Fields(Ifangcanportlet)

    def create(self, data):
        return Assignment(**data)


# NOTE: If this portlet does not have any configurable parameters, you
# can use the next AddForm implementation instead of the previous.

# class AddForm(base.NullAddForm):
#     """Portlet add form.
#     """
#     def create(self):
#         return Assignment()


# NOTE: If this portlet does not have any configurable parameters, you
# can remove the EditForm class definition and delete the editview
# attribute from the <plone:portlet /> registration in configure.zcml


class EditForm(base.EditForm):
    """Portlet edit form.

    This is registered with configure.zcml. The form_fields variable tells
    zope.formlib which fields to display.
    """
    form_fields = form.Fields(Ifangcanportlet)

